import { transformSync } from 'esbuild'
import { extname,dirname,join } from 'path'
import { existsSync } from 'fs'

export function transformCode(opts) {
  return transformSync(opts.code, {
    loader: opts.loader || 'js',
    sourcemap: true,
    format: 'esm'
  })
}

export function transformCss(opts){
  return `
    import { updateStyle } from '/@vite/client'
    const id = "${opts.path}"
    const css = "${opts.code.replace(/\n/g,'')}"
    updateStyle(id, css)
    export default css
  `
}

export function transformJSX(opts) {
  const ext = extname(opts.path).slice(1)
  const ret = transformCode({
    loader: ext,
    code: opts.code
  })
  let { code } = ret
  code = code.replace(
    /\bimport(?!\s+type)(?:[\w*{}\n\r\t, ]+from\s*)?\s*("([^"]+)"|'([^']+)')/gm,
    (a,b,c)=>{
      let from
      if(c.charAt(0) ===  '.') {
        from = join(dirname(opts.path),c)
        const filePath = join(opts.appRoot,from)
        if (!existsSync(filePath)) {
          if (existsSync(`${filePath}.js`)) {
            from = `${from}.js`
          }
        }

        if (['svg'].includes(extname(from).slice(1))) {
          from = `${from}?import`
        }
        from = from.replace(/\\/g,'/')
        console.log('from=== ',from)
      } else {
        from = `/target/.cache/${c}/cjs/${c}.development.js`
      }
      return a.replace(b, `"${from}"`)
    }
  )
  return {
    ...ret,
    code
  }
}